# -*- coding: utf-8 -*-
import copy
import random
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from zc_core.spiders.base import BaseSpider
from zc_core.dao.sku_dao import SkuDao
from zc_core.util import file_reader
from zc_core.util.http_util import retry_request
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from esgcc_sub.rules import *
from esgcc_sub.util.login import SeleniumLogin


class FullSpider(BaseSpider):
    name = 'full_part'
    # 常用链接
    # supplierId, page, startPrice, endPrice
    item_url = 'http://b.esgcc.com.cn/showDetail/{}'
    prod_detail_url = 'http://b.esgcc.com.cn/products/loadProductDetailInfomationAll?productId={}'
    prod_group_url = 'http://b.esgcc.com.cn/showDetail/getOfficeProductCompare.do?prodId={}'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        cookies = SeleniumLogin().get_cookies()
        # cookies = {'JSESSIONID': 'D0BA9F7A4BBB368B29F79EEEC8EC45EE', '__d_s_': '3CCCB516222550FEDAA106C36244C9BE', '__s_f_c_s_': '3CCCB516222550FEDAA106C36244C9BE', '__t_c_k_': '05775724b48e4729aa62cb0c195c0127'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        pool_list = SkuDao().get_batch_sku_list(self.batch_no, fields={'_id': 1, 'spuId': 1})
        self.logger.info('全量：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            spu_id = sku.get('spuId')
            # 避免无效采集
            settings = get_project_settings()
            offline_time = sku.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue

            # 采集商品价格及状态
            yield Request(
                method='POST',
                url=self.item_url.format(sku_id),
                cookies=cookies,
                callback=self.parse_item_data,
                errback=self.error_back,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'spuId': spu_id,
                },
                priority=25,
            )

    # 处理ItemData
    def parse_item_data(self, response):
        data = parse_item_data(response)
        self.logger.info('数据: [%s]' % data.get('skuId'))

        # 采商品介绍
        yield Request(
            method='POST',
            url=self.prod_detail_url.format(data.get('skuId')),
            callback=self.parse_prod_detail,
            errback=self.error_back,
            meta={
                'reqType': 'prod_detail',
                'skuId': data.get('skuId'),
                'data': copy.copy(data),
            },
            priority=50,
        )

    # 商品介绍
    def parse_prod_detail(self, response):
        data = parse_prod_detail(response)
        self.logger.info('商品: [%s]' % data.get('skuId'))
        yield data
